package com.wlcb.jpower.chat.controller.wx.mp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wlcb.jpower.chat.entity.wxapp.TblWxApp;
import com.wlcb.jpower.chat.service.wx.mp.WxAppService;
import com.wlcb.jpower.constant.DBConstant;
import com.wlcb.jpower.module.base.enums.JpowerError;
import com.wlcb.jpower.module.base.exception.JpowerAssert;
import com.wlcb.jpower.module.base.vo.ResponseData;
import com.wlcb.jpower.module.common.controller.BaseController;
import com.wlcb.jpower.module.common.page.PaginationContext;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.module.common.utils.ReturnJsonUtil;
import com.wlcb.jpower.module.common.utils.constants.JpowerConstants;
import com.wlcb.jpower.utils.WxMpInstance;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author liwenfei
 * @version V1.0
 * @date 2020/10/25 22:20
 * @desc 微信公众号
 */
@Api(tags = "微信公众号管理")
@RestController
@RequestMapping("wxapp")
@RequiredArgsConstructor
public class WxAppController extends BaseController {

    private final WxAppService wxAppService;

    /**
     * 添加微信配置信息
     *
     * @param tblWxApp
     * @return
     */
    @ApiOperation("添加微信配置信息")
    @PostMapping("add")
    public ResponseData add(TblWxApp tblWxApp) {
        JpowerAssert.notEmpty(tblWxApp.getMpName(), JpowerError.Arg,"mpName不可为空");
        JpowerAssert.notEmpty(tblWxApp.getAppId(), JpowerError.Arg,"appId不可为空");
        JpowerAssert.notEmpty(tblWxApp.getAppSecret(), JpowerError.Arg,"appSecret不可为空");
        JpowerAssert.notEmpty(tblWxApp.getToken(), JpowerError.Arg,"token不可为空");

        TblWxApp one = wxAppService.getOne(new QueryWrapper<TblWxApp>().lambda()
                .eq(TblWxApp::getAppId, tblWxApp.getAppId()).eq(TblWxApp::getIsDeleted, JpowerConstants.DB_NOT_DELETE));
        if (one != null) {
            return ReturnJsonUtil.fail("重复添加");
        }
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        configStorage.setAppId(tblWxApp.getAppId());
        configStorage.setToken(tblWxApp.getToken());
        configStorage.setAesKey(tblWxApp.getAesKey());
        configStorage.setSecret(tblWxApp.getAppSecret());
        WxMpInstance.getWxMp().addConfigStorage(tblWxApp.getAppId(), configStorage);
        return ReturnJsonUtil.status(wxAppService.save(tblWxApp));
    }

    /**
     * 更新微信配置信息
     *
     * @param tblWxApp
     * @return
     */
    @ApiOperation("更新微信配置信息")
    @PutMapping("update")
    public ResponseData update(TblWxApp tblWxApp) {
        JpowerAssert.notEmpty(tblWxApp.getId(),JpowerError.Arg,"主键不可为空");

        if (!wxAppService.update(tblWxApp, new QueryWrapper<TblWxApp>().lambda()
                .eq(TblWxApp::getId, tblWxApp.getId())
                .eq(TblWxApp::getIsDeleted, 0)
                .eq(TblWxApp::getStatus, DBConstant.EnableEnum.OPEN.getType()))) {
            return ReturnJsonUtil.fail("更新失败");
        }
        TblWxApp wxApp = wxAppService.getById(tblWxApp.getId());
        if (Fc.notNull(tblWxApp.getStatus()) && tblWxApp.getStatus().intValue() == DBConstant.EnableEnum.CLOSR.getType()) {
            WxMpInstance.getWxMp().removeConfigStorage(wxApp.getAppId());
        } else if (Fc.notNull(tblWxApp.getStatus()) && tblWxApp.getStatus().intValue() == DBConstant.EnableEnum.OPEN.getType()) {
            WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
            configStorage.setAppId(wxApp.getAppId());
            configStorage.setToken(wxApp.getToken());
            configStorage.setAesKey(wxApp.getAesKey());
            configStorage.setSecret(wxApp.getAppSecret());
            WxMpInstance.getWxMp().addConfigStorage(tblWxApp.getAppId(), configStorage);
        }
        return ReturnJsonUtil.ok("操作成功");
    }

    /**
     * 查询wxapp列表
     *
     * @param tblWxApp
     * @return
     */
    @ApiOperation("查询公众号列表")
    @GetMapping("list")
    public ResponseData<PageInfo<TblWxApp>> list(TblWxApp tblWxApp) {
        PaginationContext.startPage();
        List<TblWxApp> list = wxAppService.findList(tblWxApp);
        return ReturnJsonUtil.ok("操作成功", new PageInfo<>(list));
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation("删除公众号")
    @DeleteMapping("delete")
    public ResponseData delete(@ApiParam("主键") String id) {
        JpowerAssert.notEmpty(id,JpowerError.Arg,"主键不可为空");

        TblWxApp wxApp = wxAppService.getById(id);
        if (Fc.isNull(wxApp)) {
            return ReturnJsonUtil.fail("数据不存在");
        }
        WxMpInstance.getWxMp().removeConfigStorage(wxApp.getAppId());
        return ReturnJsonUtil.status(wxAppService.removeById(id));
    }

    @ApiOperation("查询开启的公众号")
    @GetMapping("/getOpenApp")
    public ResponseData<List<TblWxApp>> getOpenApp() {
        List<TblWxApp> list = wxAppService.list(new QueryWrapper<TblWxApp>().lambda().eq(TblWxApp::getStatus, DBConstant.EnableEnum.OPEN.getType()));
        return ReturnJsonUtil.ok("操作成功", list);
    }
}
